package com.openwater.core.db;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

import android.database.sqlite.SQLiteDatabase;

public class DBHelper {
    private static final String TAG = "DBHelper";
    private static final String DB_FILE = "common.db";
    private static final String DB_PATH = "/data/data/com.openwater/databases/" + DB_FILE;

    static {
        initDBTables();
    }

    private static synchronized SQLiteDatabase createOrOpenDatabase() {
        try {
            SQLiteDatabase db = SQLiteDatabase.openDatabase(DB_PATH, null,
                    SQLiteDatabase.OPEN_READWRITE | SQLiteDatabase.CREATE_IF_NECESSARY);
            return db;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private static void closeDatabase(SQLiteDatabase db) {
        try {
        } finally {
            if (db != null && db.isOpen()) {
                db.close();
            }
        }
    }

    private static void initDBTables() {
        SQLiteDatabase db = createOrOpenDatabase();
        db.execSQL("create table if not exists down_load_table ("
                + "id integer primary key autoincrement," + "url text," + "file_name text,"
                + "store_path text," + "status integer)");
        db.execSQL("create table if not exists file");
        // + "threadid integer, downlength integer)");
        closeDatabase(db);
    }

    public static class UserField {
        public static final String USER_TABLE = "userInfo";
        public static final String ID = "_id";
        public static final String USER_ID = "userId";
        public static final String USER_NAME = "userName";
        public static final String USER_PASSWORD = "userPassWord";
    }

    private static final String COPY_DB_PATH = "/sdcard/" + DB_FILE;

    public static void copyDB() {
        try {
            FileInputStream fis = new FileInputStream(new File(DB_PATH));
            byte[] data = new byte[fis.available()];
            File file = new File(COPY_DB_PATH);
            FileOutputStream fos = new FileOutputStream(file);
            fis.read(data);
            fos.write(data);
            fis.close();
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
